package com.rs2hd.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.rs2hd.Constants;
import com.rs2hd.model.Player;
import com.rs2hd.model.PlayerDetails;
import com.rs2hd.model.World;
import com.rs2hd.util.XStreamUtil;
import com.thoughtworks.xstream.XStream;
import com.rs2hd.model.PunishHandler;
import java.util.*;

/**
 * XML player loader/saver.
 * @author Graham
 *
 */
public class XStreamPlayerLoader implements PlayerLoader {

private static ArrayList<String> connectedIP = new ArrayList<String>();
public static PunishHandler punish = new PunishHandler();

	@Override
	public PlayerLoadResult load(PlayerDetails p) {
		XStream xstream = XStreamUtil.getXStream();
		PlayerLoadResult result = new PlayerLoadResult();
		result.returnCode = Constants.ReturnCodes.INVALID_PASSWORD;
		try  {
			Player player = (Player) xstream.fromXML(new FileInputStream("data/savedgames/"+p.getUsername()+".xml"));

			player.getPlayerDetails().setSession(p.getSession());
			{
			if(punish.isIpBanned(player.getSession()))
				punish.writeTo(player.getUsername(), "data/text/bans");
			else 
			{
				if(!player.getPlayerDetails().getPassword().equals(p.getPassword()))
					result.returnCode = Constants.ReturnCodes.INVALID_PASSWORD;
				else {
					if(World.getInstance().isOnline(p.getUsername())) {
						result.returnCode = Constants.ReturnCodes.ALREADY_ONLINE;
					} else {
						result.player = player;
						result.returnCode = Constants.ReturnCodes.LOGIN_OK;
		
					}
					if (player.banned == 2) {
						result.returnCode = Constants.ReturnCodes.BANNED;
					}
					if (player.ipbanned == 3) {
						result.returnCode = Constants.ReturnCodes.IPBANNED;
					}
				}
			}
}
		}  catch (FileNotFoundException e)  {
			result.returnCode = Constants.ReturnCodes.LOGIN_OK;
			result.player = new Player(p);
			result.player = (Player) result.player.readResolve();
		}
		return result;
	}

	@Override
	public boolean save(Player p) {
		boolean flag = true;
		try {
			XStream xstream = XStreamUtil.getXStream();
			xstream.toXML(p, new FileOutputStream("data/savedgames/"+p.getPlayerDetails().getUsername()+".xml"));
		} catch(Exception e) {
			flag = false;
		}
		return flag;
	}

}
